import json

# 找开json文件并读内容
with open('../resources/datas.json', 'r', encoding="utf-8") as f:
    # 使用json.load()把JSON文件内容转换为Python数据类型
    data = json.load(f)

# 查看转换后的结果
print(data) # {'users': [{'name': 'Jon', 'age': 20}, {'name': 'Mike', 'age': 30}]}
print(type(data))   # <class 'dict'>


print("=" * 50)
# 准备数据
dict1 = {
    "name": "Jon",
    "age": 20,
    "hobby": ["football", "swimming"],
    "is_married": False,
    "address": {
        "city": "New York",
        "country": "USA"
    },
    "skills": None
}
# 打开文件并写入内容
with open('../resources/dict1.json', 'w', encoding="utf-8") as f:
    # 使用json.dump()把Python数据类型转换为JSON文件
    # ensure_ascii=False表示把中文转为中文，而不是转成unicode编码
    # indent=4表示缩进4个空格,这样看起来更清晰
    json.dump(dict1, f, ensure_ascii=False, indent=4)
    print("写入完成")

print("=" * 50)
# json字符串转为python数据类型
json_str = ('{"name": "Jon", "age": 20, "hobby": ["football", "swimming"], '
            '"is_married": false, "address": {"city": "New York", "country": "USA"}, '
            '"skills": null}')
data = json.loads(json_str)
print(data)
print(type(data))

print("=" * 50)
# python数据类型转为json字符串
dict1 = {
    "name": "Jon",
    "age": 20,
    "hobby": ["football", "swimming"]
}
json_str = json.dumps(dict1, ensure_ascii=False, indent=4)
print(json_str)

print("=" * 50)
# 读取json文件，操作数据后再写回
with open('../resources/dict1.json', 'r', encoding="utf-8") as f:
    dict1 = json.load(f)
    # 修改内存中的python 字典数据
    dict1["age"] = 21
    dict1.update({"sex": "male"})

# 把修改后的数据写入json文件
with open('../resources/dict1.json', 'w', encoding="utf-8") as f:
    json.dump(dict1, f, ensure_ascii=False, indent=4)
    print("写入完成")
